<template>
  <div class="message-container">
    <a-card>
      <!-- 顶部操作栏 -->
      <div class="message-header">
        <div class="header-left">
          <a-button type="primary" @click="handleCompose">
            <template #icon>
              <icon-edit />
            </template>
            发送消息
          </a-button>
          <a-button @click="handleMarkAllRead" :loading="markAllLoading">
            全部已读
          </a-button>
          <a-button
            status="danger"
            :disabled="!selectedKeys.length"
            @click="handleBatchDelete"
          >
            <template #icon>
              <icon-delete />
            </template>
            批量删除
          </a-button>
        </div>
        
        <div class="header-right">
          <a-badge :count="unreadCount" :max-count="99">
            <a-button @click="refreshMessages">
              <template #icon>
                <icon-refresh />
              </template>
              刷新
            </a-button>
          </a-badge>
        </div>
      </div>

      <!-- 消息筛选 -->
      <div class="message-filters">
        <a-radio-group v-model="filters.type" @change="handleFilterChange">
          <a-radio :value="null">全部</a-radio>
          <a-radio :value="1">系统通知</a-radio>
          <a-radio :value="2">站内信</a-radio>
          <a-radio :value="3">公告</a-radio>
        </a-radio-group>
        
        <a-radio-group v-model="filters.status" @change="handleFilterChange">
          <a-radio :value="null">全部状态</a-radio>
          <a-radio :value="0">未读</a-radio>
          <a-radio :value="1">已读</a-radio>
        </a-radio-group>
      </div>

      <!-- 消息列表 -->
      <a-table
        :columns="columns"
        :data="messageList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        row-key="id"
      >
        <template #type="{ record }">
          <a-tag :color="getTypeColor(record.type)">
            {{ getTypeText(record.type) }}
          </a-tag>
        </template>

        <template #title="{ record }">
          <div class="message-title" :class="{ 'unread': record.status === 0 }">
            <icon-pushpin v-if="record.isTop" class="pin-icon" />
            {{ record.title }}
          </div>
        </template>

        <template #status="{ record }">
          <a-tag :color="record.status === 0 ? 'red' : 'green'">
            {{ record.status === 0 ? '未读' : '已读' }}
          </a-tag>
        </template>

        <template #priority="{ record }">
          <a-tag :color="getPriorityColor(record.priority)">
            {{ getPriorityText(record.priority) }}
          </a-tag>
        </template>

        <template #actions="{ record }">
          <a-button size="small" @click="handleRead(record)">
            {{ record.status === 0 ? '标记已读' : '查看' }}
          </a-button>
          <a-popconfirm
            content="确定要删除这条消息吗？"
            @ok="handleDelete(record)"
          >
            <a-button size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <!-- 发送消息弹窗 -->
    <a-modal
      v-model:visible="composeVisible"
      title="发送消息"
      width="600px"
      @ok="handleSend"
      @cancel="handleComposeCancel"
    >
      <a-form
        ref="composeFormRef"
        :model="composeForm"
        :rules="composeRules"
        layout="vertical"
      >
        <a-form-item label="消息类型" field="type">
          <a-select v-model="composeForm.type" placeholder="请选择消息类型">
            <a-option :value="1">系统通知</a-option>
            <a-option :value="2">站内信</a-option>
            <a-option :value="3">公告</a-option>
          </a-select>
        </a-form-item>

        <a-form-item label="接收者" field="receiverId">
          <a-select
            v-model="composeForm.receiverId"
            placeholder="请选择接收者"
            :loading="userLoading"
            allow-search
          >
            <a-option
              v-for="user in userList"
              :key="user.id"
              :value="user.id"
              :label="user.realName"
            >
              {{ user.realName }} ({{ user.username }})
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item label="优先级" field="priority">
          <a-select v-model="composeForm.priority" placeholder="请选择优先级">
            <a-option :value="1">低</a-option>
            <a-option :value="2">中</a-option>
            <a-option :value="3">高</a-option>
          </a-select>
        </a-form-item>

        <a-form-item label="消息标题" field="title">
          <a-input v-model="composeForm.title" placeholder="请输入消息标题" />
        </a-form-item>

        <a-form-item label="消息内容" field="content">
          <a-textarea
            v-model="composeForm.content"
            placeholder="请输入消息内容"
            :rows="6"
            :max-length="1000"
            show-word-limit
          />
        </a-form-item>

        <a-form-item label="标签" field="tags">
          <a-input v-model="composeForm.tags" placeholder="多个标签用逗号分隔" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 消息详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="消息详情"
      width="800px"
      :footer="false"
    >
      <div v-if="selectedMessage" class="message-detail">
        <div class="detail-header">
          <h3>{{ selectedMessage.title }}</h3>
          <div class="detail-meta">
            <a-tag :color="getTypeColor(selectedMessage.type)">
              {{ getTypeText(selectedMessage.type) }}
            </a-tag>
            <a-tag :color="getPriorityColor(selectedMessage.priority)">
              {{ getPriorityText(selectedMessage.priority) }}
            </a-tag>
            <span class="sender">发送者：{{ selectedMessage.senderName }}</span>
            <span class="time">{{ selectedMessage.createTime }}</span>
          </div>
        </div>
        
        <div class="detail-content" v-html="selectedMessage.content"></div>
        
        <div v-if="selectedMessage.tags" class="detail-tags">
          <span class="tags-label">标签：</span>
          <a-tag
            v-for="tag in selectedMessage.tags.split(',')"
            :key="tag"
            size="small"
          >
            {{ tag.trim() }}
          </a-tag>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'
import { messageApi, userApi } from '@/api'

// 数据状态
const loading = ref(false)
const messageList = ref([])
const selectedKeys = ref<string[]>([])
const unreadCount = ref(0)

// 筛选条件
const filters = reactive({
  type: null,
  status: null
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showTotal: true
})

// 表格配置
const columns: TableColumnData[] = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '类型', slotName: 'type', width: 100 },
  { title: '标题', slotName: 'title', width: 300 },
  { title: '发送者', dataIndex: 'senderName', width: 120 },
  { title: '状态', slotName: 'status', width: 80 },
  { title: '优先级', slotName: 'priority', width: 80 },
  { title: '发送时间', dataIndex: 'createTime', width: 160 },
  { title: '操作', slotName: 'actions', width: 160, fixed: 'right' }
]

// 行选择配置
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  onSelect: (rowKeys: string[]) => {
    selectedKeys.value = rowKeys
  },
  onSelectAll: (checked: boolean) => {
    if (checked) {
      selectedKeys.value = messageList.value.map((item: any) => item.id)
    } else {
      selectedKeys.value = []
    }
  }
})

// 发送消息相关
const composeVisible = ref(false)
const composeFormRef = ref()
const composeForm = reactive({
  type: 2,
  receiverId: null,
  priority: 2,
  title: '',
  content: '',
  tags: ''
})

const composeRules = {
  type: [{ required: true, message: '请选择消息类型' }],
  receiverId: [{ required: true, message: '请选择接收者' }],
  title: [{ required: true, message: '请输入消息标题' }],
  content: [{ required: true, message: '请输入消息内容' }]
}

// 用户列表
const userList = ref([])
const userLoading = ref(false)

// 消息详情
const detailVisible = ref(false)
const selectedMessage = ref(null)

// 其他状态
const markAllLoading = ref(false)

// 工具方法
const getTypeColor = (type: number) => {
  const colors = { 1: 'blue', 2: 'green', 3: 'orange' }
  return colors[type] || 'gray'
}

const getTypeText = (type: number) => {
  const texts = { 1: '系统通知', 2: '站内信', 3: '公告' }
  return texts[type] || '未知'
}

const getPriorityColor = (priority: number) => {
  const colors = { 1: 'gray', 2: 'blue', 3: 'red' }
  return colors[priority] || 'gray'
}

const getPriorityText = (priority: number) => {
  const texts = { 1: '低', 2: '中', 3: '高' }
  return texts[priority] || '未知'
}

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      type: filters.type,
      status: filters.status
    }
    
    const { data } = await messageApi.getMessagePage(params)
    messageList.value = data.records
    pagination.total = data.total
    
    // 获取未读数量
    const unreadRes = await messageApi.getUnreadCount()
    unreadCount.value = unreadRes.data
  } catch (error) {
    Message.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const fetchUsers = async () => {
  userLoading.value = true
  try {
    const { data } = await userApi.getUserList()
    userList.value = data
  } catch (error) {
    Message.error('获取用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 事件处理
const handleFilterChange = () => {
  pagination.current = 1
  fetchMessages()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  fetchMessages()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchMessages()
}

const handleCompose = () => {
  composeVisible.value = true
  if (userList.value.length === 0) {
    fetchUsers()
  }
}

const handleComposeCancel = () => {
  composeVisible.value = false
  resetComposeForm()
}

const resetComposeForm = () => {
  Object.assign(composeForm, {
    type: 2,
    receiverId: null,
    priority: 2,
    title: '',
    content: '',
    tags: ''
  })
  composeFormRef.value?.clearValidate()
}

const handleSend = async () => {
  const errors = await composeFormRef.value?.validate()
  if (errors) return

  try {
    await messageApi.sendMessage(composeForm)
    Message.success('消息发送成功')
    composeVisible.value = false
    resetComposeForm()
    fetchMessages()
  } catch (error) {
    Message.error('消息发送失败')
  }
}

const handleRead = async (record: any) => {
  if (record.status === 0) {
    // 标记为已读
    try {
      await messageApi.markAsRead(record.id)
      record.status = 1
      record.readTime = new Date().toLocaleString()
      unreadCount.value = Math.max(0, unreadCount.value - 1)
      Message.success('已标记为已读')
    } catch (error) {
      Message.error('操作失败')
    }
  }
  
  // 显示详情
  selectedMessage.value = record
  detailVisible.value = true
}

const handleDelete = async (record: any) => {
  try {
    await messageApi.deleteMessage(record.id)
    Message.success('删除成功')
    fetchMessages()
  } catch (error) {
    Message.error('删除失败')
  }
}

const handleBatchDelete = async () => {
  if (!selectedKeys.value.length) return

  try {
    await messageApi.batchDeleteMessage({ ids: selectedKeys.value })
    Message.success('批量删除成功')
    selectedKeys.value = []
    fetchMessages()
  } catch (error) {
    Message.error('批量删除失败')
  }
}

const handleMarkAllRead = async () => {
  markAllLoading.value = true
  try {
    await messageApi.markAllAsRead()
    Message.success('全部消息已标记为已读')
    unreadCount.value = 0
    fetchMessages()
  } catch (error) {
    Message.error('操作失败')
  } finally {
    markAllLoading.value = false
  }
}

const refreshMessages = () => {
  fetchMessages()
}

onMounted(() => {
  fetchMessages()
})
</script>

<style lang="scss" scoped>
.message-container {
  padding: 20px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .header-left {
    .arco-btn + .arco-btn {
      margin-left: 8px;
    }
  }
}

.message-filters {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f7f8fa;
  border-radius: 6px;
}

.message-title {
  display: flex;
  align-items: center;
  
  &.unread {
    font-weight: bold;
    color: #165dff;
  }
  
  .pin-icon {
    margin-right: 4px;
    color: #ff7d00;
  }
}

.message-detail {
  .detail-header {
    border-bottom: 1px solid #e5e6eb;
    padding-bottom: 16px;
    margin-bottom: 16px;

    h3 {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
    }

    .detail-meta {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 12px;
      color: #86909c;

      .sender, .time {
        font-size: 12px;
      }
    }
  }

  .detail-content {
    line-height: 1.6;
    margin-bottom: 16px;
    white-space: pre-wrap;
  }

  .detail-tags {
    .tags-label {
      color: #86909c;
      margin-right: 8px;
    }
  }
}
</style> 